class LoginController < ApplicationController
    def index
        
    end


	def make_user
		user = User.find(:first, :conditions => [ "username = ?", params[:username]])
		if params[:password] == "" or params[:password] == nil      #check password validity
			flash[:notice] = "Password can not be empty."
			redirect_to :controller => :login, :action => :index
            return
		end
		if params[:firstname] == "" or params[:lastname] == "" or params[:username] == ""
			flash[:notice] = "Please fill out ALL fields."
			redirect_to :controller => :login, :action => :index
            return
		end
		if isValidEmail(params[:email]) != 0      #check email validity
			redirect_to :controller => :login, :action => :index
            return
		end
		if (user == nil and params[:username] != "")
            Person.create(:firstname => params[:firstname], :surname => params[:surname], :user => params[:username])
            if nil == User.find(:all)
    			User.create(:username => params[:username], :password => params[:password], :role => 1)
    			flash[:notice] = "New Admin user was created. Please login now."
            else
    			User.create(:username => params[:username], :password => params[:password], :role => 2)
    			flash[:notice] = "New user was created. Please login now."
			end
			Contact.create(:email => params[:email])
			redirect_to :controller => :login, :action => :index
		else
			flash[:notice] = "User #{params[:username]} already exists."
			session[:loggedin] = false
			redirect_to :controller => :home, :action => :index
		end
	end
    
    
	def authorize 
#		unless session[:loggedin] == true #&& session[:loginrole] == "admin" 
#			flash[:notice] = "Please log in" 
#			redirect_to :controller => :login, :action => :index 
#		end 
	end 
	
	
	def login_user
		user = User.find(:first, :conditions => [ "username = ?", params[:username]])
		if (user != nil && user.password == params[:password])
			session[:loggedin] = true
			session[:loginname] = user.username
			session[:loginuid] = user.id
			role = Role.find(:first, :conditions => [ "id = ?", user.role])   
			session[:loginrole] = role.description
			redirect_to :controller => :home, :action => :index
		else
			flash[:notice] = "Username/Password Incorrect"
			session[:loggedin] = false
    		redirect_to :controller => :login, :action => :index
		end
	end
	
	
	def logout
		reset_session
		session[:loggedin] = false
		redirect_to :controller => :login, :action => :index
	end 
	
private
    def isValidEmail(email)
        if email == ""
            flash[:notice] = "email can not be empty<br />"
            return 2
        elsif email.index('@') == nil or email.index('.') == nil
            flash[:notice] = "invalid email<br />"            
            return 1
        else
            return 0
        end
    end
	
	
end
